import axios from 'axios'
export default {
	state() {
		return {
			list: []
		}
	},
	mutations: {
		changeList(state, list) {
			state.list = list
		},
		updateCount(state, obj) {
			var itemObj = state.list.find((item) => item.id == obj.id)
			itemObj.count = obj.count
		}
	},
	actions: {
		async getList({ commit }) {
			const res = await axios('http://192.168.87.184:3000/cart')
			console.log(res, 8888)
			commit('changeList', res.data)
		},
		async syncCount({ commit }, obj) {
			// const res = await axios.patch('http://192.168.87.184:3000/cart/' + obj.id, {
			// 	count: obj.count
			// })
			// console.log('id', obj.id, res)
			// commit('updateCount', obj)

			return new Promise(async (resolve, reject) => {
				const res = await axios.patch('http://192.168.87.184:3000/cart/' + obj.id, {
					count: obj.count
				})
				/* 这里写的代码表示成功之后执行的代码 相当于.then函数中执行的代码 */
				resolve(res)
			})
		}
	},
	getters: {
		total(state) {
			return state.list.reduce((sum, item) => sum + item.count, 0)
		},
		totalPrice(state) {
			return state.list.reduce((sum, item) => sum + item.count * item.price, 0)
		}
	},
	namespaced: true
}
